package com.bobo.nutzbook.module;

import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import cn.apiclub.captcha.Captcha;
import cn.apiclub.captcha.backgrounds.GradiatedBackgroundProducer;
import cn.apiclub.captcha.gimpy.FishEyeGimpyRenderer;
import cn.apiclub.captcha.text.renderer.DefaultWordRenderer;

import com.bobo.nutzbook.util.Toolkit;

@IocBean
@At("/captcha")
public class CaptchaModule {

	@At
	@Ok("raw:png")
	public BufferedImage next(@Param("w") int w, @Param("h") int h, HttpSession session)
	{
		if (w * h < 1) //长或宽为0?重置为默认长宽.
		{
			w = 120;
			h = 60;
		}
		
		//自定义设置字体颜色和大小，多种字体随机显示 
		List<Font> fontList = new ArrayList<Font>();
		fontList.add(new Font("Courier", Font.BOLD, 36));
		fontList.add(new Font("Arial", Font.ITALIC, 32));
		fontList.add(new Font("Times New Roman", Font.PLAIN, 40));
		List<Color> colorList = new ArrayList<Color>();
		colorList.add(Color.BLACK);
		colorList.add(new Color(55, 55, 55));
		colorList.add(new Color(33, 33, 33));
		
		Captcha captcha = new Captcha.Builder(w, h).addText(new DefaultWordRenderer(colorList, fontList))
												.addBackground(new GradiatedBackgroundProducer())
												.gimp(new FishEyeGimpyRenderer())
												.build();
		String text = captcha.getAnswer();
		session.setAttribute(Toolkit.captcha_attr, text);
		return captcha.getImage();
	}
}
